/**
 * Author shuqi
 * Rev
 * Date: 2021-08-18 23:05
 * <p>
 * Copyright (C) 2021 Seeyon, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of Seeyon, Inc.
 * Use is subject to license terms.
 * @company seeyon.com
 * @since V5 V7.1
 * @author shuqi
 */
package com.lagou.config;

import com.google.common.collect.Maps;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Map;

/**
 * @description
 * @date 2021-08-18 23:05
 * @author xiaol
 */
public class ServletConfig {

	private static Map<String,String> servletMapper = Maps.newHashMap();

	private final static String NAME = "web.xml";

	public static Map<String, String> getServletMapper() {
		return servletMapper;
	}

	public static void initConfig(){
		ServerConfig.ServiceConfig serviceConfig = ServerConfig.getServiceConfig();
		String appBase = serviceConfig.getHost().getAppBase();
		Map<String, Map<String, ServerConfig.Context>> configs = serviceConfig.getConfig();
		String classpath = ServletConfig.class.getResource("/").getPath();
		int index = classpath.lastIndexOf("target");
		String substring = classpath.substring(0, index);
		String basePath = substring + "src/main";
		configs.forEach((k,v) -> v.forEach((c, t) -> {
			String path = basePath + "/" + appBase + "/" + t.getDocBase();
			try {
				getConfig(k + t.getApplicationContext(),path);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}));
	}

	/**
	 * 解析web.xml
	 * @param path
	 */
	private static void getConfig(String prefix,String path) throws DocumentException {
		SAXReader saxReader = new SAXReader();
		Document read = saxReader.read(new File(path + "/" + NAME));
		Element root = read.getRootElement();
		Element servlet = root.element("servlet");
		Element servletClassElement = servlet.element("servlet-class");
		String servletClass = servletClassElement.getText();

		Element servletMapping = root.element("servlet-mapping");
		Element urlElement = servletMapping.element("url-pattern");
		String url = urlElement.getText();
		servletMapper.put(prefix + url,servletClass);
	}


}
